<template>
  <div class="app-container multi-footer">
    <div>
      <el-select v-model="year" placeholder="请选择" size="small" @change="getData()">
        <el-option
          v-for="item in selectOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </div>
    <div class="filter-container">
      <el-button
        type="primary"
        size="mini"
        plain
        icon="el-icon-plus"
        @click="handleAdd"
      >
        新增
      </el-button>
      <el-button
        type="success"
        size="mini"
        plain
        icon="el-icon-edit"
        :disabled="buttonState.editDisabled"
        @click="handleUpdate()"
      >
        修改
      </el-button>
      <el-button
        type="danger"
        size="mini"
        plain
        icon="el-icon-delete"
        :disabled="buttonState.delDisabled"
        @click="handleDelete()"
      >
        删除
      </el-button>
      <right-toolbar @queryTable="getData"></right-toolbar>
    </div>
    <el-table
      :data="tableData"
      show-summary
      :summary-method="getSummaries"
      style="width: 100%"
      ref="salaryTable"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      @sort-change='sortChange'
      :default-sort = "{prop: 'issueYear', order: 'descending'}"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        label="序号"
        width="50"
        align="center"
      >
        <template slot-scope="scope">
          {{ (page - 1) * pageSize + scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        align="center"
        width="350"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="salaryMicrometer" label="工资(元)" width="150">
        <template slot-scope="scope">
          <el-tag type="primary">￥{{ scope.row.salaryMicrometer }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="issueYear"
        label="年份"
        align="center"
        width="150"
        sortable="custom"
        sort-by="issue_year"
        :sort-orders="['ascending', 'descending']"
      ></el-table-column>
      <el-table-column
        prop="issueMonth"
        label="月份"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="issueDate"
        label="工资发放日期"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row.salaryId)">
            修改
          </el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.salaryId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="totalCount>0"
      :total="totalCount"
      :page.sync="page"
      :limit.sync="pageSize"
      @pagination="getData"
    />

    <!-- 新增或修改工资对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form :model="form" ref="form" :rules="rules" label-width="80px">
        <input type="hidden" v-model="form.salaryId" />
        <el-form-item label="工资" prop="salary">
          <el-input-number
            style="width: 100%"
            v-model="form.salary"
            placeholder="请输入工资"
            :min="1"
            :max="99999999.99"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="发放日期" prop="issueDate">
          <el-date-picker
            v-model="form.issueDate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择发放日期"
            :editable="false"
            class="el-date-picker-custom"
            :clearable="false"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            placeholder="请输入备注，空则自动生成"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="submitForm" :disabled="buttonState.submitDisabled">确 定</el-button>
        <el-button @click.native="cancelHandler">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'HistorySalary',
  data() {
    return {
      tableData: null,
      pageTotal: null,
      total: null,
      totalCount: 0,
      year: -1,
      page: 1,
      pageSize: 10,
      asc: false,
      buttonState: {
        editDisabled: true,
        delDisabled: true,
        submitDisabled: false
      },
      loading: true,
      ids: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单验证规则
      rules: {
        salary: [
          {
            required: true,
            message: '请输入正确的工资，范围1-99999999.99',
            trigger: 'blur',
          },
        ],
        issueDate: [
          { required: true, message: '请选择发放日期', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 排序
    sortChange(column, prop, order) {
      if (column.order == 'ascending') {
        this.asc = true;
      } else {
        this.asc = false;
      }
      this.getData();
    },
    // 删除
    handleDelete(salaryId) {
      this.$confirm('此操作将永久删除该条工资记录 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = salaryId || this.ids
        this.deleteRequest(`/salary/my/${id}`).then(() => {
          // 判断删除之后页码数是否发生变化
          let totalPage = 0; 
          if (id instanceof Array) {
            // 批量删除
            totalPage = Math.ceil((this.totalCount - id.length) / this.pageSize); // 剩余数据总页数
            this.totalCount -= id.length;
          } else {
            // 单条删除
            totalPage = Math.ceil((this.totalCount - 1) / this.pageSize); // 剩余数据总页数
            this.totalCount -= 1;
          }

          this.page = this.page > totalPage ? totalPage : this.page
          this.page = this.page < 1 ? 1 : this.page

          this.getData()
        })
      }).catch(() => {});
    },
    // 打开修改对话框
    handleUpdate(salaryId) {
      this.title = "修改工资"
      let id = salaryId || this.ids[0]
      this.getRequest(`/salary/my/${id}`).then((resp) => {
        this.form = resp.data;
        this.open = true;
      })
    },
    // 新增/修改工资
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonState.submitDisabled = true
          if (!this.form.salaryId) {
            // 新增
            this.postRequest("/salary/my/", this.form).then(() => {
              this.open = false;
              this.buttonState.submitDisabled = false
              // 新增成功，跳转到最后一页
              this.totalCount += 1;
              let totalPage = Math.ceil(this.totalCount / this.pageSize);
              this.page = this.page > totalPage ? this.page : totalPage
              this.getData()
            }).catch(() => {
              this.buttonState.submitDisabled = false
            })
          } else {
            // 修改
            this.putRequest('/salary/my/', this.form).then(() => {
              this.open = false
              this.buttonState.submitDisabled = false
              this.getData()
            }).catch(() => {
              this.buttonState.submitDisabled = false
            })
          }
        }
      });
    },
    // 关闭新增对话框
    cancelHandler() {
      this.open = false
      setTimeout(() => {
        this.reset()
      }, 200)
    },
    // 打开新增对话框
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增工资'
    },
    // 重置表单
    reset() {
      this.form = {
        issueDate: this.parseTime(new Date(), '{yyyy}-{mm}-{dd}'),
      }
      this.resetForm('form')
    },
    // 复选框选择
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.salaryId)
      if (this.ids.length <= 0) {
        this.buttonState.delDisabled = true
      } else {
        this.buttonState.delDisabled = false
      }

      if (this.ids.length == 1) {
        this.buttonState.editDisabled = false
      } else {
        this.buttonState.editDisabled = true
      }
    },
    getData() {
      this.loading = true
      this.getRequest(
        `/salary/history/${this.year}?page=${this.page}&limit=${this.pageSize}&asc=${this.asc}`
      ).then((resp) => {
        this.tableData = resp.data.list.result
        this.pageTotal = resp.data.list.pageTotal
        this.total = resp.data.list.total
        this.totalCount = Number(resp.data.total)
        this.loading = false
      })
    },
    getSummaries(param) {
      const { columns, data } = param

      const sums = []

      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = (
            <div class="footer-body">
              <span class="summary-title">当前页合计</span>
              <span class="border-summary" />
              <span class="summary-title">总计</span>
            </div>
          )
          return
        }

        if (column.property === 'salaryMicrometer') {
          sums[index] = (
            <div class="footer-body">
              <span class="summary-title">
                <el-tag type="primary">￥{this.pageTotal} 元</el-tag>
              </span>
              <span class="border-summary" />
              <span class="summary-title">
                <el-tag type="primary">￥{this.total} 元</el-tag>
              </span>
            </div>
          )
        } else {
          sums[index] = <div class="border-summary"></div>
        }
      })
      return sums
    },
  },
  computed: {
    selectOptions() {
      let options = [
        {
          value: -1,
          label: '全部',
        },
      ]
      const year = new Date().getFullYear()
      for (let i = year; i >= 1990; i--) {
        options.push({
          value: i,
          label: i + '年历史工资',
        })
      }

      return options
    },
  },
}
</script>

<style lang="scss" scoped>

</style>
